package com.central.apps.handler.project;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理产出计划管理业务逻辑
 *
 * @author lidachao
 * @date 2023/2/1
 */
@Component
@Slf4j
public class ProjectOutputplanHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {
        if ("gq_prooutputplan".equals(objName)) {
            Integer id = MapUtils.getInteger(data, "id");
            Integer proId = MapUtils.getInteger(data, "proid");

            StringBuilder sbSql = new StringBuilder();
            sbSql.append("select id from gq_prooutputplan where status != '已作废' and proid = ").append(proId);
            if (id != null) {
                sbSql.append(" and id != ").append(id);
            }
            // 查询是否已经存在产出计划申请
            List<Map<String, Object>> list = handlerService.findBySql(sbSql.toString());

            if (CollectionUtils.isNotEmpty(list)) {
                return "已经存在产出计划数据, 不能再新建数据!";
            }
        }
        return null;
    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if ("capture".equals(flowNode.getId())) {
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_prooutputplandetail where popid = " + id);

            if (CollectionUtils.isEmpty(list)) {
                return "请维护产出计划明细信息!";
            }
        }

        if("complete".equals(flowNode.getId()) && op.isFlag()) {
            List<Map<String, Object>> list = handlerService.findBySql("select proid from gq_prooutputplan where id = " + id);
            Map<String, Object> map = list.get(0);
            Integer proid = MapUtils.getInteger(map, "proid");

            list = handlerService.findBySql("select id from gq_prooutputplandetail where popid = " + id);

            int count = 0;
            if (CollectionUtils.isNotEmpty(list)) {
                count = list.size();
            }

            handlerService.updateBySql("update gq_proaccount set prototaldocs = " + count + ", doctotalongoing = " + count + " where id = " + proid);
        }

        return null;
    }
}
